Ext.define("Triends.Model.Triendslist",{
	extend: "Ext.data.Model",
	config: {
		idProperty: "ID",
		fields: [
			"ID", "Name", "Email", "Age", "Gender", "Introduction", "Cacao" , "UserTheme", "Distance", "Time", "Theme", "Total", "Wifi"
		]
	}
});



var TriendsStore = Ext.create("Ext.data.Store",{
	model: "Triends.Model.Triendslist",
	id: 'TriendsStore',
	clearOnPageLoad: false,
	pageSize: 20
});

Ext.define('Triends.view.TriendsList', {
	extend: 'Ext.dataview.DataView',
	alias: 'triendslist',
	xtype: 'triendslist',
	id: 'triendslist',
	config: {
		fullscreen: true,
		store: TriendsStore,
		requires: ['Ext.plugin.ListPaging', 'Ext.plugin.PullRefresh'],
		plugins: [
				{type: 'listpaging', autoPaging:true, clearOnPageLoad: false, loadMoreText: 'Next..'},
				{type: 'pullrefresh' /*refreshFn: function(plugin){postStore.load()}*/}
		],
		limit: 20,
		style: 'background:white',
		useComponents: true,
		defaultType: 'TriendsListItem',
		loadingText: false,
//		scrollable: false,
		width: '100%',
		listeners: {
			initialize: function() {
				
    			var wrapper = this.getScrollable().getElement();
   				
   				var unloader = new Unloader(wrapper, '.x-container x-data-item');

				var masterScroll = new iScroll(wrapper.getId(), {
    				onRefresh: function() {
        				unloader.setup(this.x, this.y);
    				},
    				onPositionChange: function(x, y) {
        				unloader.onmove(x, y); 
    				}
				});
				this.getScrollable().setScroller(masterScroll);
			
			}
		},
		items: [{
			xtype: 'titlebar',
			height: 48,
			docked: 'top',
			ui: 'light',
			items: [{
				xtype: 'panel',
				flex: 6
			},{
				xtype: 'panel',
				id: 'triendstheme',
				align: 'right',
				height: 25,
				width: 25
			},{
 				 xtype: 'selectfield',
				 width: 120,
				 align: 'right',
				 inputCls: 'selectfield',
				 usePicker: false,
				 id: 'triendslisttheme',
				 options: [
			 		{text: '식사', value: 1},
			 		{text: '술', value: 2},
			 		{text: '야경', value: 3},
			 		{text: '공연관람', value: 4},
			 		{text: '쇼핑', value: 5},
			 		{text: '클러빙', value: 6},
			 		{text: '전체', value: 7}
			 	 ],
			 	 listeners:{
			 	 	change: function(selectbox, newValue, oldValue){
			 	 		var usertheme = newValue.get('value');
			 	 		Ext.getCmp('triendstheme').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
	        				
	        			var userthemepanel = Ext.getCmp('userthemepanel');
						userthemepanel.setSrc('resource/images/'+usertheme+'.png');
			 	 		//로그인 이후 테마 변경하는 경우 실행
		 	 			if (usertheme != UserStore.getAt(0).data.UserTheme) {
		 	 				
				 	 		Ext.Viewport.setMasked({
								xtype: 'loadmask',
	    						indicator: true
							});
				 	 		
			 	 			UserStore.getAt(0).data.UserTheme = usertheme ;
			 	 			
			 	 			var userid = UserStore.getAt(0).data.ID;
			 	 			
							var TriendsStore = Ext.getStore('TriendsStore');
							var tingStore = Ext.getStore('tingstore');
							TriendsStore.removeAll();
							tingStore.removeAll();
							
							navigator.geolocation.getCurrentPosition(function(position){
								
								UserStore.getAt(0).data.UserLat = position.coords.latitude;
								UserStore.getAt(0).data.UserLng = position.coords.longitude;
	       						var userlat = UserStore.getAt(0).data.UserLat
	           					var userlng = UserStore.getAt(0).data.UserLng
	           					
	           					TriendsStore.setProxy({
									type: "jsonp",
									url: 'http://itscreater.cafe24.com/Triends/TriendsList.jsp',
									callbackkey: 'callback',
									extraParams: {
										userid: userid,
										userlat:userlat,
	        							userlng:userlng,
	        							usertheme: usertheme
									},
									pageParam: 'pages',
									limitParam: 'rpp',
									reader: {
										type: "json",
										rootProperty: "results",
										totalProperty: "total"
									}
								});
								
	    						tingStore.setProxy({
									type: "jsonp",
									url: 'http://itscreater.cafe24.com/Triends/TingList.jsp',
									extraParams: {
										userlat: userlat, 
										userlng:userlng, 
										usertheme: usertheme
									},
									callbackkey: 'callback',
				 					pageParam: 'pages',
									limitParam: 'rpp',
									reader: {
										type: "json",
										rootProperty: "results",
										totalProperty: "total"
									}
								});
								
								tingStore.loadPage(1, {
									callback: function() {
										TriendsStore.loadPage(1);
										Ext.data.JsonP.request({
				    						url: 'http://itscreater.cafe24.com/Triends/UserThemeUpdate.jsp',
			        						params: {
				        						userid: userid,
			        							userlat:userlat,
			            						userlng:userlng,
			            						usertheme: usertheme
			        						},
			        						callbackKey: 'callback',
			        						success: function(result) {
												var userlatlng = new google.maps.LatLng(userlat, userlng);
								
												geocoder.geocode({'latLng':userlatlng}, function(results, status){
													if (status == google.maps.GeocoderStatus.OK) {
						   								if (results[1]) {
						   									var usercityname = results[1].address_components[2].long_name;
						 									var userlocationpanel = Ext.getCmp('userlocationpanel');
															userlocationpanel.setHtml("<font size='2'>"+usercityname+"</font>");
						   								}
													}
												});
												
												setTimeout(function() {
													Ext.Viewport.setMasked(false);
												}, 1500);
			        						}
			           					});
									}
								});
	           				}, function(error) {console.log(error.code+error.message)});
			 	 		}
			 	 		
			 	 		// 사용자가 TriendsList에서 테마를 변경한 경우 - TingList 테마 바꾸기 실행
	           			if (usertheme != Ext.getCmp('tinglisttheme').getValue()) {
	           				Ext.getCmp('tinglisttheme').setValue(usertheme);
	           			}
			 	 	}
			 	 }
			}]
		}]
	}
});

Ext.define('TriendsListItem', {
	extend: 'Ext.dataview.component.DataItem',
    xtype: 'TriendsListItem',	
	config: {
		listeners: {
			updatedata: function() {
				var otherid = this.getRecord().get('ID');
				var triendsname = this.getRecord().get('Name');
				var triendsintro = this.getRecord().get('Introduction');
				
				var img = this.getItems().items[0].getItems().items[0];
				var triendsnamepanel = this.getItems().items[1].getItems().items[0];
				var triendsintropanel = this.getItems().items[1].getItems().items[1];
				var tfipicturepanel = this.getItems().items[3].getItems().items[0];
				img.setHtml('<img src="https://graph.facebook.com/'+otherid+'/picture?width=64&height=64">');
				triendsnamepanel.setHtml("<font size='3'><b>"+triendsname+"</b></font>");
				if (triendsintro != null){
					if (triendsintro.match("<br>")){
						triendsintro = triendsintro.replace(/<br>/gi, " ");
					}
				}
				else {
					triendsintro = ''
				}
				triendsintropanel.setHtml('<div class="triendsellipsis"><nobr><font size="2">'+triendsintro+'</font></nobr></div>');
				
				var Tvalue = this.getRecord().get('Total');
				var Tpanel = this.getItems().items[2];
				Tpanel.setHtml("<font size='2'><b>"+Tvalue+"%</b></font>");
				
				var wifi = this.getRecord().get('Wifi');
				tfipicturepanel.setHtml("<img src='resource/images/wifi"+wifi+".png' width='40px' height='40px'>");
			}
		},
		layout: 'hbox',
		width: '100%',
		minHeight: 80,
		style: 'background:white;border-bottom:1px #CBCAC7 solid;',
		items: [
		{
			xtype: 'panel',
			width: 80,
			style: 'padding-top: 7px; padding-left: 7px;',
			listeners: {
				tap: {
					element: 'element',
					fn: function() {
						Ext.Viewport.setMasked({
							xtype: 'loadmask',
					    	indicator: true
						});
						var dataitem = this.getParent();
						dataitem.setStyle("background:#CBCAC7");
						setTimeout(function(){dataitem.setStyle('background:white;border-bottom:1px #CBCAC7 solid;')},200);
						
						setTimeout(function(){
							var otherid	= dataitem.getRecord().get('ID');
							openOtherinfo(otherid);
							var othertfipanel = Ext.getCmp('othertfipanel');
						}, 500);
					}
				}
			},
			items: [{
				xtype: 'panel',
				style: 'padding-top:4px;',
				height: 64,
				width: 64
			}]
		},
		{
			xtype: 'panel',
			width: '100%',
			style: 'padding-bottom:10px;',
			layout: 'vbox',
			listeners: {
				tap: {
					element: 'element',
					fn: function() {
						Ext.Viewport.setMasked({
							xtype: 'loadmask',
					    	indicator: true
						});
						var dataitem = this.getParent();
						dataitem.setStyle("background:#CBCAC7");
						setTimeout(function(){dataitem.setStyle('background:white;border-bottom:1px #CBCAC7 solid;')},200);
						
						setTimeout(function(){
							var otherid	= dataitem.getRecord().get('ID');
							openOtherinfo(otherid);
							var othertfipanel = Ext.getCmp('othertfipanel');
						}, 500);
					}
				}
			},
			items:[{
				xtype: 'panel',
				style: 'word-break:break-all;padding-top:10px;'
			},
			{
				xtype: 'panel',
				minHeight: 30,
				style: 'word-break:break-all;margin-top:10px;',
				listeners: {
					tap: {
						element: 'element',
						fn: function() {
							var dataitem = this.getParent().getParent();
							var otherid = dataitem.getRecord().get('ID');
							openOtherinfo(otherid);
							var othertfipanel = Ext.getCmp('othertfipanel');
						}
					}
				}
			}]
		},
		{
			xtype: 'panel',
			width: 40,
			style: 'word-break:break-all;padding-right:10px;padding-top:30px;text-align:center;',
			docked: 'right',
			listeners: {
				tap: {
					element: 'element',
					fn: function() {
						var dataitem = this.getParent();
						var record = dataitem.getRecord();
						
						var Tdetail = Ext.create('Triends.view.Tdetail');
						var Tfidistance = Ext.getCmp('Tfidistance');
						var Tfitime = Ext.getCmp('Tfitime');
						var Tfitheme = Ext.getCmp('Tfitheme');
						var distance = record.get("Distance").split(".")[0];
				    	var time = record.get("Time").split(".")[0];
				    	if (time < 60){
				    		Tfitime.setHtml("<font size='5'>"+time+"</font>분 전")
				    	}else if(time > 60 && time < 1440){
				    		time = time/60;
				    		time = Math.round(time);
				    		Tfitime.setHtml("<font size='5'>"+time+"</font>시간 전")
				    	}else if(time > 1440){
				    		time = time/1440;
				    		time = Math.round(time);
				    		Tfitime.setHtml("<font size='5'>"+time+"</font>일 전")
				    	}
				    	var theme = record.get("UserTheme");
				    	Tfidistance.setData({Distance: distance});
				    	Tfitheme.setHtml('<img src="resource/images/'+theme+'.png">');
				    	console.log(theme);
				    	Ext.Viewport.add(Tdetail);
					}
				}
			}
		},
		{
			xtype: 'panel',
			layout: 'vbox',
			docked: 'right',
			style: 'margin-right:5px; padding-left:-10px;',
			items:[{
				xtype: 'panel',
				style: 'margin-top:10px;',
				width: 40,
				listeners: {
						tap: {
							element: 'element',
							fn: function() {
								var dataitem = this.getParent().getParent();
								var record = dataitem.getRecord();
								
								var Tdetail = Ext.create('Triends.view.Tdetail');
								var Tfidistance = Ext.getCmp('Tfidistance');
								var Tfitime = Ext.getCmp('Tfitime');
								var Tfitheme = Ext.getCmp('Tfitheme');
								var distance = record.get("Distance").split(".")[0];
						    	var time = record.get("Time").split(".")[0];
						    	if (time < 60){
						    		Tfitime.setHtml("<font size='5'>"+time+"</font>분 전")
						    	}else if(time > 60 && time < 1440){
						    		time = time/60;
						    		time = Math.round(time);
						    		Tfitime.setHtml("<font size='5'>"+time+"</font>시간 전")
						    	}else if(time > 1440){
						    		time = time/1440;
						    		time = Math.round(time);
						    		Tfitime.setHtml("<font size='5'>"+time+"</font>일 전")
						    	}
						    	var theme = record.get("UserTheme");
						    	Tfidistance.setData({Distance: distance});
						    	Tfitheme.setHtml('<img src="resource/images/'+theme+'.png">');
						    	console.log(theme);
						    	Ext.Viewport.add(Tdetail);
							}
						}
				}
			},
			{
				xtype: 'panel',
				style: 'text-align:center;margin-top:-10px;',
				html: 'T-fi',
				listeners: {
						tap: {
							element: 'element',
							fn: function() {
								var dataitem = this.getParent().getParent();
								var record = dataitem.getRecord();
								
								var Tdetail = Ext.create('Triends.view.Tdetail');
								var Tfidistance = Ext.getCmp('Tfidistance');
								var Tfitime = Ext.getCmp('Tfitime');
								var Tfitheme = Ext.getCmp('Tfitheme');
								var distance = record.get("Distance").split(".")[0];
						    	var time = record.get("Time").split(".")[0];
						    	if (time < 60){
				    				Tfitime.setHtml("<font size='5'>"+time+"</font>분 전")
						    	}else if(time > 60 && time < 1440){
						    		time = time/60;
						    		time = Math.round(time);
						    		Tfitime.setHtml("<font size='5'>"+time+"</font>시간 전")
						    	}else if(time > 1440){
						    		time = time/1440;
						    		time = Math.round(time);
						    		Tfitime.setHtml("<font size='5'>"+time+"</font>일 전")
						    	}
						    	var theme = record.get("UserTheme");
						    	Tfidistance.setData({Distance: distance});
						    	Tfitheme.setHtml('<img src="resource/images/'+theme+'.png">');
						    	Ext.Viewport.add(Tdetail);
							}
						}
				}
			}]
		}]
    }
});

Ext.define('Triends.view.Tdetail', {
	extend: 'Ext.Panel',
	xtype: 'Tdetail',
	id: 'Tdetail',
	config: {
    	modal: true,
    	top: '10%',
    	left: '50%',
    	layout: 'vbox',
    	style: 'margin-left:-150px',
		hideOnMaskTap: true,
		width: 300,
		height: 350,
		listeners: {
			hide: function() {
				this.destroy();
			}
		},
    	items: [{
    		xtype: 'titlebar',
    		docked: 'top',
    		title: '<div class="title"><font size="3">T-fi 구성요소</font></div>'
    	},
    	{
    		xtype: 'panel',
    		style: 'padding:10px',
    		layout: 'vbox',
    		items: [{
    			xtype: 'panel',
    			html: '<font size="3"><b>거리</b></font>'
    		},
    		{
    			xtype: 'panel',
    			id: 'Tfidistance',
    			width: '100%',
    			style: 'margin-top:10px;text-align:center',
    			tpl: "<font size='5'>{Distance}</font> km"
    		},
    		{
    			xtype: 'panel',
    			style: 'margin-top:30px',
    			html: '<font size="3"><b>업데이트 시간</b></font>'
    		},
    		{
    			xtype: 'panel',
    			id: 'Tfitime',
    			width: '100%',
    			style: 'margin-top:10px;text-align:center'
    		},
    		{
    			xtype: 'panel',
    			style: 'margin-top:30px',
    			html: '<font size="3"><b>Theme</b></font>'
    		},
    		{
    			xtype: 'panel',
    			width: '100%',
    			items:[{
    				xtype: 'panel',
		    		style: 'left:50%; margin-left:-24px',
	    			id: 'Tfitheme',
	    			width: 48
    			}]
    		}]
    	}]
	}
});
